package cn.tedu.knows.portal.controller;


import cn.tedu.knows.portal.exception.ServiceException;
import cn.tedu.knows.portal.model.Answer;
import cn.tedu.knows.portal.service.IAnswerService;
import cn.tedu.knows.portal.vo.AnswerVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2021-10-27
 */
@RestController
@RequestMapping("/v1/answers")
@Slf4j
public class AnswerController {
    @Autowired
    private IAnswerService answerService;
    @PostMapping("")
    //@PreAuthorize("hasAnyAuthority('/question/answer')")
    //hasRole是特指验证角色的指令
    //ROLE_开头的auth就是角色的标志
    //hasRole验证时可以将role_省略直接写它后面的内容
    //但是他的判断也不死板hasRole（'ROLE_TEACHER'）也可以
    @PreAuthorize("hasRole('TEACHER')")
    public Answer postAnswer(
            @Validated AnswerVo answerVo,
            BindingResult result,
            @AuthenticationPrincipal UserDetails user){
        log.debug("表单信息：{}",answerVo);
        if (result.hasErrors()){
            String msg =result.getFieldError().getDefaultMessage();
            throw new ServiceException(msg);
        }
        //这里调用逻辑层
       Answer answer= answerService.saveAnswer(answerVo,user.getUsername());
        return answer;
    }
    @GetMapping("/question/{id}")
    public List<Answer> questionAnswers(
            @PathVariable Integer id){
        List<Answer> answers=answerService.getAnswersByQuestionId(id);
        return answers;
    }
}
